//index.js  
//获取应用实例  
var app = getApp();
Page({
    data: {
        status: "",
        sousuo: "",
        connectedDeviceId: "", //已连接设备uuid  
        services: "", // 连接设备的服务  
        characteristics: "", // 连接设备的状态值  
        writeServicweId: "", // 可写服务uuid  
        writeCharacteristicsId: "", //可写特征值uuid  
        readServicweId: "", // 可读服务uuid  
        readCharacteristicsId: "", //可读特征值uuid  
        notifyServicweId: "", //通知服务UUid  
        notifyCharacteristicsId: "", //通知特征值UUID  
        inputValue: "",
        characteristics1: "", // 连接设备的状态值  
        str: [],
        number1:"",
        itemDetail: '',
        codes2: [], //装车条码
        codes: [], //比对条码
        index:1,
        scanCodeType:'',//扫码类型
        lists:[]//比对条码
    },
    onShow(){
      var that=this
      that.lanya1()
    },
    onLoad: function(options) {
        var that = this
        //var itemDetail = JSON.parse(options.item);

        //var tokenL = wx.getStorageSync("TOKEN")
        // this.setData({
        //     itemDetail: itemDetail,
        //     scanCodeType: options.index
        // })

        // console.log(itemDetail, "logs-------")
        // var ordersList = []
        // for (var i = 0; i < itemDetail.length; i++) {
        //     ordersList[i] = Object.assign({ id: itemDetail[i].orderId });
        // }
        // console.log(ordersList, "--------")

        // wx.request({
        //     url: app.globalData.apiServer + "/api/Orders/GetCodesAndClientCodeByBatchOrder",
        //     data: {
        //         ordersList
        //     },
        //     method: "POST",
        //     header: {
        //         'content-type': 'application/json',
        //         "Authorization": "Bearer " + tokenL,
        //         "LoginType": 4
        //     },
        //     success: function(res) {
        //         if (res.data.responseCode == 1000) {
        //             that.setData({
        //                 lists: res.data.obj //
        //             })
        //             console.log(that.data.lists)
        //         } else {
        //             wx.showToast({
        //                 title: res.data.msg,
        //                 icon: 'none',
        //                 duration: 2000
        //             });
        //         }

        //     }

        // })


        if (wx.openBluetoothAdapter) {
            wx.openBluetoothAdapter()
        } else {
            // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示  
            wx.showModal({
                title: '提示',
                content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
            })
        }


        // wx.getBluetoothDevices({ //自动连接蓝牙设备
        //     success: function(res) {
        //         console.log(res, "自动连接蓝牙设备")
        //         if (res.devices[0]) {
        //             console.log(that.ab2hex(res.devices[0].advertisData))
        //         }
        //     }
        // })
        // 初始化蓝牙适配器 
        setTimeout(() => {
          that.lanya1()
        }, 2000)
     
    },
    // 初始化蓝牙适配器  
    lanya1: function() {
      console.log("lanya1")
        var that = this;
        wx.openBluetoothAdapter({
            success: function(res) {
                that.setData({
                        msg: "初始化蓝牙适配器成功！" + JSON.stringify(res),
                    })
                    //监听蓝牙适配器状态  
                wx.onBluetoothAdapterStateChange(function(res) {

                    that.setData({
                        sousuo: res.discovering ? "在搜索。" : "未搜索。",
                        status: res.available ? "可用。" : "不可用。",
                    })


                })
                that.lanya2()
            }
        })
    },
    // 本机蓝牙适配器状态  
    lanya2: function() {
        var that = this;
        wx.getBluetoothAdapterState({
            success: function(res) {
                that.setData({
                        msg: "本机蓝牙适配器状态" + "/" + JSON.stringify(res.errMsg),
                        sousuo: res.discovering ? "在搜索。" : "未搜索。",
                        status: res.available ? "可用。" : "不可用。",
                    })
                    //监听蓝牙适配器状态  
                wx.onBluetoothAdapterStateChange(function(res) {
                    that.setData({
                        sousuo: res.discovering ? "在搜索。" : "未搜索。",
                        status: res.available ? "可用。" : "不可用。",
                    })

                })
                that.lanya3()
            }
        })
    },
    //搜索设备  
    lanya3: function() {
        var that = this;
        wx.startBluetoothDevicesDiscovery({
            success: function(res) {
                that.setData({
                        msg: "搜索设备" + JSON.stringify(res),
                    })
                    //监听蓝牙适配器状态  
                wx.onBluetoothAdapterStateChange(function(res) {
                    that.setData({
                        sousuo: res.discovering ? "在搜索。" : "未搜索。",
                        status: res.available ? "可用。" : "不可用。",
                    })

                })
                that.lanya4()
            }
        })
    },
    // 获取所有已发现的设备  
    lanya4: function() {
        var that = this;
        wx.getBluetoothDevices({
            success: function(res) {
                //是否有已连接设备  
                wx.getConnectedBluetoothDevices({
                    success: function(res) {
                        that.setData({
                            connectedDeviceId: res.deviceId
                        })
                    }
                })
                that.setData({
                        msg: "搜索设备" + JSON.stringify(res.devices),
                        devices: res.devices,
                        // getBLEDeviceServices
                    })
                    //监听蓝牙适配器状态  
                wx.onBluetoothAdapterStateChange(function(res) {
                    that.setData({
                        sousuo: res.discovering ? "在搜索。" : "未搜索。",
                        status: res.available ? "可用。" : "不可用。",
                    })
                })
            }
        })
    },
    //停止搜索周边设备  
    lanya5: function() {
        var that = this;
        wx.stopBluetoothDevicesDiscovery({
            success: function(res) {
                that.setData({
                    msg: "停止搜索周边设备" + "/" + JSON.stringify(res.errMsg),
                    sousuo: res.discovering ? "在搜索。" : "未搜索。",
                    status: res.available ? "可用。" : "不可用。",
                })
            }
        })
    },
    //连接设备  
    connectTO: function(e) {
        var that = this;
        wx.createBLEConnection({
            deviceId: e.currentTarget.id,
            success: function(res) {
                that.setData({
                    connectedDeviceId: e.currentTarget.id,
                    msg: "已连接" + e.currentTarget.id,
                    msg1: "",
                })
                if (res.errMsg == "createBLEConnection:ok") {
                  app.globalData.deviceId = e.currentTarget.id
                    wx.showToast({
                        title: '设备连接成功',
                        icon: 'loading',
                        duration: 2000
                    });

                } else {
                    wx.showToast({
                        title: '设备连接失败',
                        icon: 'loading',
                        duration: 2000
                    });
                }
            },
            fail: function() {
                wx.showToast({
                    title: '设备连接失败',
                    icon: 'loading',
                    duration: 2000
                });
            },
            complete: function() {
                console.log("调用结束");
            }

        })
    },
    // 获取连接设备的service服务  
    lanya6: function() {
        var that = this;
        wx.getBLEDeviceServices({
            // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取  
            deviceId: that.data.connectedDeviceId,
            success: function(res) {
                that.setData({
                    services: res.services,
                    msg: JSON.stringify(res.services),
                })
                var cId = "0000fff4-0000-1000-8000-00805f9b34fb";
                wx.notifyBLECharacteristicValueChanged({
                    deviceId: that.data.connectedDeviceId,
                    serviceId: "0000fff0-0000-1000-8000-00805f9b34fb",
                    characteristicId: "0000fff4-0000-1000-8000-00805f9b34fb",
                    state: true,
                    success: function(res) {
                        // success
                        wx.onBLECharacteristicValueChange(function(res) {
                            that.getCodeByte(res.value)
                        }, function(res) {})

                        that.lanya7()
                    },
                    fail: function(res) {},
                    complete: function(res) {
                        // complete
                    }
                })
            }
        })
    },
    //获取连接设备的所有特征值  for循环获取不到值  
    lanya7: function() {
        var that = this;
        wx.getBLEDeviceCharacteristics({
            // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取  
            deviceId: that.data.connectedDeviceId,
            // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取  
            serviceId: "0000fff0-0000-1000-8000-00805f9b34fb",
            success: function(res) {
                for (var i = 0; i < res.characteristics.length; i++) {
                    if (res.characteristics[i].properties.notify || res.characteristics[i].properties.indicate) {
                        that.setData({
                            notifyServicweId: that.data.services[0].uuid,
                            notifyCharacteristicsId: res.characteristics[i].uuid,
                        })
                    }
                    if (res.characteristics[i].properties.write) {
                        that.setData({
                            writeServicweId: that.data.services[0].uuid,
                            writeCharacteristicsId: res.characteristics[i].uuid,
                        })

                    } else if (res.characteristics[i].properties.read) {
                        that.setData({
                            readServicweId: that.data.services[0].uuid,
                            readCharacteristicsId: res.characteristics[i].uuid,
                        })

                    }
                }

                that.setData({
                    msg: JSON.stringify(res.characteristics),

                })
            },
            fail: function() {},
            complete: function() {}
        })
        if (that.data.services.length > 0) {
            wx.getBLEDeviceCharacteristics({
                // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取  
                deviceId: that.data.connectedDeviceId,
                // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取  
                serviceId: "0000fff0-0000-1000-8000-00805f9b34fb",
                success: function(res) {
                    for (var i = 0; i < res.characteristics.length; i++) {
                        if (res.characteristics[i].properties.notify || res.characteristics[i].properties.indicate) {
                            that.setData({
                                notifyServicweId: that.data.services[1].uuid,
                                notifyCharacteristicsId: res.characteristics[i].uuid,
                            })
                        }
                        if (res.characteristics[i].properties.write) {
                            that.setData({
                                writeServicweId: that.data.services[1].uuid,
                                writeCharacteristicsId: res.characteristics[i].uuid,
                            })

                        } else if (res.characteristics[i].properties.read) {
                            that.setData({
                                readServicweId: that.data.services[1].uuid,
                                readCharacteristicsId: res.characteristics[i].uuid,
                            })

                        }
                    }

                    that.setData({
                        //msg1: JSON.stringify(res.characteristics),
                        msg1: '可以扫描'
                    })
                },
                fail: function() {
                    console.log("fail1");
                },
                complete: function() {
                    console.log("complete1");
                }
            })
        }

    },
    //断开设备连接  
    lanya0: function() {
        var that = this;
        wx.closeBLEConnection({
            deviceId: that.data.connectedDeviceId,
            success: function(res) {
                that.setData({
                    connectedDeviceId: "",
                })
            }
        })
    },
    //监听input表单  
    inputTextchange: function(e) {
        this.setData({
            inputValue: e.detail.value
        })
    },
    lanya9: function() {
        var that = this;

    },
    onBLECharacteristicValueChange: function(cId) {
        var that = this
        wx.onBLECharacteristicValueChange(function(res) {
            that.getCodeByte(res.value)
        })

    },
    //接收消息  
    lanya10: function() {
        var that = this;

        function ab2hex(buffer) {
            var hexArr = Array.prototype.map.call(
                new Uint8Array(buffer),
                function(bit) {
                    return ('00' + bit.toString(16)).slice(-2)
                }
            )
            return hexArr.join('');
        }
        wx.onBLECharacteristicValueChange(function(res) {

            that.getCodeByte(res.value)
        })
        wx.readBLECharacteristicValue({
            // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取  
            deviceId: that.data.connectedDeviceId,
            // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取  
            serviceId: that.data.readServicweId,
            // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取  
            characteristicId: that.data.readCharacteristicsId,
            success: function(res) {
                console.log('readBLECharacteristicValue:', res.errMsg);
            }
        })

    },
    getCodeByte: function(arrayBuffer) {
        var that = this
        var dataView = new DataView(arrayBuffer)
        for (var i = 0; i < arrayBuffer.byteLength; i++) {
            if (arrayBuffer.byteLength > 3 && dataView.getUint8(0) == 0x40 && dataView.getUint8(2) == 0x53 && dataView.getUint8(3) == 0x01 && dataView.getUint8(arrayBuffer.byteLength - 1) == 0x2A) {
                if (i > 3 && i < arrayBuffer.byteLength - 3) {
                    that.data.index = i
                    that.data.str[that.data.index] = dataView.getUint8(i)
                }
            } else if (arrayBuffer.byteLength > 3 && dataView.getUint8(0) == 0x40 && dataView.getUint8(2) == 0x53 && dataView.getUint8(3) == 0x01) {
                if (i > 3 && dataView.getUint8(i) != 121) {
                    that.data.index = i
                    that.data.str[that.data.index] = dataView.getUint8(i)
                }
            } else if (dataView.getUint8(0) != 0x40 && dataView.getUint8(arrayBuffer.byteLength - 1) == 0x2A) {
                if (i < arrayBuffer.byteLength - 3) {
                    that.data.index++
                        that.data.str[that.data.index] = dataView.getUint8(i)
                }
            } else {
                if (dataView.getUint8(i) != 121) {
                    that.data.index++
                        that.data.str[that.data.index] = dataView.getUint8(i)
                }
            }
        }
        if ((dataView.getUint8(0) != 0x40 && dataView.getUint8(arrayBuffer.byteLength - 1) == 0x2A) || (dataView.getUint8(0) == 0x40 && dataView.getUint8(2) == 0x53 && dataView.getUint8(3) == 0x01 && dataView.getUint8(arrayBuffer.byteLength - 1) == 0x2A)) {
            that.getCurrentNumberString(that.data.str)
        }
    },
    getCurrentNumberString: function() {
        var tokenL = app.globalData.token
        console.log("--------------222","执行扫描")
        var that = this
        var codes2 = that.data.codes2;
        var tostring = ""

        // if (array.length > 4 && array[0] == 0x40 && array[2] == 0x53 && array[3] == 0x01 && array[that.data.index] == 0x2A) {
        //console.log(that.Trim(tostring),"that.data.str-----")
        tostring = String.fromCharCode.apply(String, that.data.str);
        console.log(tostring.substring(4), "that.data.str-----")
        that.setData({
            str: [],
            number1: tostring
        })
        console.log(that.data.number1.substring(4),that.data.number1.length,"logsssss扫描条码")
        // if (that.data.number1) {
        //   if (that.data.lists.length && that.data.lists[0].codeList.length){
        //     for (var i = 0; i < that.data.lists[i].length; i++) {
        //       for (var j = 0; j < that.data.lists[i].codeList.length;j++){
        //         if (that.data.number1 != that.data.lists[i].codeList[j]) {
        //           console.log("不存在")
        //           wx.showToast({
        //             title: '不存在条码',
        //             icon: 'none',
        //             duration: 2000
        //           });
        //         }else{
        //           console.log("成功")
        //           wx.showToast({
        //             title: '扫码成功',
        //             icon: 'none',
        //             duration: 2000
        //           });                  
              //    app.globalData.scanCodeList.push(that.data.number1)
        app.getCode(tostring.substring(4))
        //         }
        //       }

        //     }
        //   }else{
        //     wx.showToast({
        //       title: '不存在条码',
        //       icon: 'none',
        //       duration: 2000
        //     });
        //   }

        // }
    },

  


          // wx.request({
          //   url: app.globalData.apiServer + "/api/ScanCode/Scan",
          //   data: {
          //     orderId: that.data.itemDetail[0].orderId, //关联的订单id
          //     goodsId: that.data.itemDetail[0].id, //关联的货物id
          //     scanCodeType: that.data.scanCodeType, //关联的扫码类型
          //     code: that.data.number1, //扫码单号
          //     //code: '6951957202020D-W2'
          //     //remark: ''//备注
          //   },
          //   method: "POST",
          //   header: {
          //     'content-type': 'application/json',
          //     "Authorization": "Bearer " + tokenL,
          //     "LoginType": 4
          //   },
          //   success: function (res) {
          //     if (res.data.responseCode == 1000) {
          //       wx.showToast({
          //         title: '取件扫码成功',
          //         icon: 'loading',
          //         duration: 2000
          //       });
          //     } else {
          //       wx.showToast({
          //         title: '扫码失败',
          //         icon: 'none',
          //         duration: 2000
          //       });
          //     }
          //   }
          // })
    //   }
    // },

    onUnload: function() {
        var that = this

        app.globalData.code2 = that.data.codes2
    },


    // ArrayBuffer转16进度字符串示例
    ab2hex(buffer) {
        var hexArr = Array.prototype.map.call(
            new Uint8Array(buffer),
            function(bit) {
                return ('00' + bit.toString(16)).slice(-2)
            }
        )
        return hexArr.join('');
    },
    unique1(array){ 
    var n = []; //一个新的临时数组 
    //遍历当前数组 
    for(var i = 0; i<array.length; i++){ 
      //如果当前数组的第i已经保存进了临时数组，那么跳过， 
      //否则把当前项push到临时数组里面 
      if (n.indexOf(array[i]) == -1) n.push(array[i]);
    }
    return n; 
    },
    trim(str)
    { 
      let newStr = str.split('');
      newStr = newStr.filter((item, index) => {
        console.log(item);
        return item != " "
      })
      // return str.replace(/(^\s*)|(\s*$)/g, ""); 
      return newStr.join('');
    }

})